// 导入ol
import TileGrid from 'ol/tilegrid/tilegrid';
import TileLayer from 'ol/layer/tile';
import olProj from 'ol/proj';
import TileImage from 'ol/source/tileimage';
const config = {
  minZoom: 1, //最层级
  maxZoom: 18, //最小层级
  sourceProjection: 'EPSG:3857', // 数据源的分辨率
  viewProjection: 'EPSG:4326', // 视图的分辨率
  origin: [0, 0],
};

/**
 * 获取百度地图分辨率 resolutions
 * @returns {Object} resolutions
 */
const bMapResolutions = function () {
  let resolutions = [];
  for (let i = 0; i <= config.maxZoom; i++) {
    resolutions[i] = Math.pow(2, config.maxZoom - i);
  }
  return resolutions;
};

/**
 * 默认地图样式(normal)
 * 清新蓝风格(light)
 * 黑夜风格(dark)
 * 红色警惕风格(redalert)
 * 精简风格(googlelite)
 * 天然绿风格(grassgreen)
 * 午夜蓝风格(midnight)
 * 浪漫粉风格(pink)
 * 青春绿风格(darkgreen)
 * 清新蓝绿风格(bluish)
 * 高端灰风格(grayscale)
 * 强边界风格(hardedge)
 */

function getBaiduCustomimage(customid) {
  //   debugger;
  var projection = olProj.get(config.sourceProjection);
  var resolutions = bMapResolutions();
  var tilegrid = new TileGrid({
    origin: config.origin,
    resolutions: resolutions,
  });

  var baidu_source = new TileImage({
    projection: projection,
    tileGrid: tilegrid,
    tileUrlFunction: function (tileCoord) {
      if (!tileCoord) {
        return '';
      }
      var z = tileCoord[0];
      var x = tileCoord[1];
      var y = tileCoord[2];

      if (x < 0) {
        x = 'M' + -x;
      }
      if (y < 0) {
        y = 'M' + -y;
      }
      return (
        'http://api2.map.bdimg.com/customimage/tile?&x=' +
        x +
        '&y=' +
        y +
        '&z=' +
        z +
        '&udt=20170428&scale=1&ak=E4805d16520de693a3fe707cdc962045&customid=' +
        customid
      );
    },
  });
  return new TileLayer({
    source: baidu_source,
  });
}
const baidu_layer = getBaiduCustomimage('normal');

// baiduMap 百度地图配置
export const bMapTileConfig = {
  baidu_layer,
  defaultJd: '121.488014', //默认经度
  defaultWd: '31.09651', //默认纬度
  defaultZoom: 9, //地图默认显示层级
  ...config,
};
